package com.st.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.st.pojo.User;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.HashMap;

@Component
public class JWTUtil {
    private String jwtKey = "lc";

    public HashMap<String, String> cerateToken(Integer id) {
        HashMap<String, String> token = getToken(id);
        return token;
    }



    public HashMap<String, String> getToken(Integer id){
        HashMap<String, Object> map = new HashMap<>();
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.MINUTE, 30);
        String token = JWT.create()
                .withHeader(map)
                .withClaim("id",id)
                .withExpiresAt(instance.getTime()) //将过期时间设定给jwt，每次验证都需要校验其是否超过此时间，超过即失效
                .sign(Algorithm.HMAC256(jwtKey));//签名，需要使用开发者定义的密钥
        //定义一个存储token和过期时间的map
        HashMap<String, String> map1 = new HashMap<>();
        map1.put("token", token);
        map1.put("expiresTime", String.valueOf(instance.getTime().getTime()));
//        map1.put("id",user.getId());
//        map1.put("imagpath",user.getimagpath());
//        map1.put("icon",user.getIcon());
        return map1;
    }

    /**
     * 验证token,只去校验该token是否为当前服务颁发
     *
     * @param token
     */
    public void verify(String token) {
        JWT.require(Algorithm.HMAC256(jwtKey)).build().verify(token);
    }

    /**
     * 获取token中payload
     *
     * @param token
     * @return
     */
    public DecodedJWT getToken(String token) {
        return JWT.require(Algorithm.HMAC256(jwtKey)).build().verify(token);
    }
}
